package com.yes.yll.servlet;

import com.yes.yll.JdbcUtils;
import org.apache.commons.lang3.RandomStringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;

public class GoodsAdd extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("n");
        String price = req.getParameter("p");
        String id = req.getParameter("id");
        Part img = req.getPart("i");

        String fileName = img.getSubmittedFileName();
        String[] strings = fileName.split("\\.");
        String suffix = strings[1];
        String imga = RandomStringUtils.randomAlphabetic(10) + "." + suffix;

        img.write(imga);

        if(id!=null && !"null".equals(id)){
            //存在id，更新
            String sql="UPDATE goods SET `name`=?,price=? WHERE id=?";
            JdbcUtils.modify(sql,name,price,id);
        }else{
            // 不存在id 新增
          /*  String sql="INSERT INTO good(name,price,`name`) VALUES(?,MD5('123456'),?)";
            JdbcUtils.modify(sql,z,n);*/
            String sql = "INSERT INTO goods(`name`,price,image)VALUES(?,?,?)";
            JdbcUtils.modify(sql,name,price,imga);
        }

        resp.sendRedirect("/yll/user-list.jsp");
    }



    }
